#include "gameroom.h"
#include "gameselect.h"
#include <QPainter>
#include <QPixmap>
#include <QIcon>
#include <QTimer>
#include <QPushButton>
#include <QMessageBox>
#include <QFile>
#include <QFile>
#include <QTextStream>
#include <QKeyEvent>
#include <QWidget>
#include <QDebug>

GameRoom::GameRoom(QWidget *parent) : QWidget(parent)
{
    this->setFixedSize(1500,1200); // 设置窗口大小
    this->setWindowIcon(QIcon(":res/res/ico.png")); // 设置窗口图标
    this->setWindowTitle("游戏房间"); // 设置窗口标题

    // 初始化贪吃蛇
    snakeList.push_back(QRectF(this->width()*0.5,this->height()*0.5,kSnakeNodeWidth,kSnakeNodeHeight));

    moveUp();
    moveUp();

    // 创建食物
    createNewFood();

    timer=new QTimer(this);

    connect(timer,&QTimer::timeout,[=](){
        int cnt=1;

        if(snakeList.front().intersects(foodRect))
        {
            createNewFood();
            ++cnt;

             QSound::play(":res/res/eatfood.wav");
        }

        while(cnt--)
        {
            switch(moveDirect)
            {
                case SnakeDirect::UP:
                    moveUp();
                    break;
                case SnakeDirect::DOWN:
                    moveDown();
                    break;
                case SnakeDirect::LEFT:
                    moveLeft();
                    break;
                case SnakeDirect::RIGHT:
                    moveRight();
                    break;
                default:
                    break;
            }
        }

        snakeList.pop_back(); // 删除最后一个节点
        update();
    });

    QFont font("黑体",20);

    // 开始游戏
    QPushButton *strBtn=new QPushButton(this);
    strBtn->move(1250,250);
    strBtn->setText("开始");
    strBtn->setFont(font);

    connect(strBtn,&QPushButton::clicked,[=](){
        isGameStart=true;
        timer->start(moveTimeout);
        sound=new QSound(":res/res/Trepak.wav");
        sound->play();
        sound->setLoops(-1);

    });

    // 暂停游戏
    QPushButton *stopBtn=new QPushButton(this);
    stopBtn->move(1250,400);
    stopBtn->setText("暂停");
    stopBtn->setFont(font);

    connect(stopBtn,&QPushButton::clicked,[=](){
        isGameStart=false;
        timer->stop();
        sound->stop();
    });

    // 蛇方向的控制
    QPushButton *up=new QPushButton(this);
    QPushButton *down=new QPushButton(this);
    QPushButton *left=new QPushButton(this);
    QPushButton *right=new QPushButton(this);

    up->move(1280,660);
    down->move(1280,800);
    left->move(1200,730);
    right->move(1360,730);

    up->setText("↑");
    down->setText("↓");
    left->setText("←");
    right->setText("→");

    up->setStyleSheet("QPushButton{border:0px}");
    down->setStyleSheet("QPushButton{border:0px}");
    left->setStyleSheet("QPushButton{border:0px}");
    right->setStyleSheet("QPushButton{border:0px}");

    QFont ft("华文琥珀",36);
    up->setFont(ft);
    down->setFont(ft);
    left->setFont(ft);
    right->setFont(ft);

    connect(up,&QPushButton::clicked,[=](){
        if(moveDirect!=SnakeDirect::DOWN)
            moveDirect=SnakeDirect::UP;
    });

    connect(down,&QPushButton::clicked,[=](){
        if(moveDirect!=SnakeDirect::UP)
            moveDirect=SnakeDirect::DOWN;
    });

    connect(left,&QPushButton::clicked,[=](){
        if(moveDirect!=SnakeDirect::RIGHT)
            moveDirect=SnakeDirect::LEFT;
    });

    connect(right,&QPushButton::clicked,[=](){
        if(moveDirect!=SnakeDirect::LEFT)
            moveDirect=SnakeDirect::RIGHT;
    });



    // 退出游戏
    QPushButton *ExitBtn=new QPushButton(this);
    ExitBtn->move(1250,1000);
    ExitBtn->setText("退出");
    ExitBtn->setFont(font);

    QMessageBox *msg=new QMessageBox(this);
    QPushButton *ok=new QPushButton("ok");
    QPushButton *cancel=new QPushButton("cancel");

    msg->addButton(ok,QMessageBox::AcceptRole);
    msg->addButton(cancel,QMessageBox::RejectRole);

    msg->setWindowTitle("退出游戏");
    msg->setText("确认退出游戏吗？");

    connect(ExitBtn,&QPushButton::clicked,[=](){
        msg->show();
        msg->exec(); // 事件轮询
        QSound::play(":/res/res/clicked.wav");

        GameSelect *select=new GameSelect;

        if(msg->clickedButton()==ok)
        {
            this->close();
            select->show();
        }
        else
        {
            msg->close();
        }
    });
}

void GameRoom::keyPressEvent(QKeyEvent* event)
{
    switch (event->key())
    {
        // 键盘的方向键'上'或大小写'w/W'
        case Qt::Key_Up:
        case 'w':
        case 'W':
        if(moveDirect!=SnakeDirect::DOWN)
            moveDirect=SnakeDirect::UP;
        break;

        // 键盘的方向键'下'或大小写's/S'
        case Qt::Key_Down:
        case 's':
        case 'S':
        if(moveDirect!=SnakeDirect::UP)
            moveDirect=SnakeDirect::DOWN;
        break;


        // 键盘的方向键'左'或大小写'a/A'
        case Qt::Key_Left:
        case 'a':
        case 'A':
        if(moveDirect!=SnakeDirect::RIGHT)
            moveDirect=SnakeDirect::LEFT;
        break;


        // 键盘的方向键'右'或大小写'd/D'
        case Qt::Key_Right:
        case 'd':
        case 'D':
        if(moveDirect!=SnakeDirect::LEFT)
            moveDirect=SnakeDirect::RIGHT;
        break;

    }
}

void GameRoom::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);

    QPixmap pix;

    pix.load(":res/res/game_room.png");
    painter.drawPixmap(0,0,1150,1200,pix);

    pix.load(":res/res/bg1.png");
    painter.drawPixmap(1150,0,350,1250,pix);

    // 绘制蛇 蛇头+蛇身体+蛇尾
    if(moveDirect==SnakeDirect::UP)
    {
        pix.load(":res/res/up.png");
    }
    else if(moveDirect==SnakeDirect::DOWN)
    {
        pix.load(":res/res/down.png");
    }
    else if(moveDirect==SnakeDirect::LEFT)
    {
        pix.load(":res/res/left.png");
    }
    else // moveDirect==SnakeDirect::RIGHT
    {
        pix.load(":res/res/right.png");
    }

    auto snakeHead=snakeList.front();
    painter.drawPixmap(snakeHead.x(),snakeHead.y(),snakeHead.width(),snakeHead.height(),pix);

    // 绘制蛇身
    pix.load(":res/res/Bd.png");
    for(int i=1;i<snakeList.size()-1;i++)
    {
        auto node=snakeList.at(i);
        painter.drawPixmap(node.x(),node.y(),node.width(),node.height(),pix);
    }

    // 绘制蛇尾
    auto snakeTail=snakeList.back();
    painter.drawPixmap(snakeTail.x(),snakeTail.y(),snakeTail.width(),snakeTail.height(),pix);

    // 绘制食物
    pix.load(":res/res/food.bmp");
    painter.drawPixmap(foodRect.x(),foodRect.y(),foodRect.width(),foodRect.height(),pix);

    // 绘制分数
    pix.load(":res/res/sorce_bg.png");
    painter.drawPixmap(this->width()*0.85,this->height()*0.06,90,40,pix);

    QPen pen;
    pen.setColor(Qt::black);
    painter.setPen(pen);

    QFont font("黑体",22);
    painter.setFont(font);
    painter.drawText(this->width()*0.88,this->height()*0.1,QString("%1").arg(snakeList.size()));

    // 往文件中写内容
    int c=snakeList.size();
    QFile file("D:\Qt\qt\greedy_snake\Snake\history.txt");
    if(file.open(QIODevice::WriteOnly|QIODevice::Text))
    {
        QTextStream out(&file);
        int num=c;
        out<<num;
        file.close();
    }

    // 绘制游戏失败
    if(checkFail())
    {
        pen.setColor(Qt::red);
        painter.setPen(pen);
        QFont font("黑体",50);
        painter.setFont(font);
        painter.drawText(this->width()*0.3,this->height()*0.5,QString("GAME OVER!"));
        timer->stop();
        QSound::play(":res/res/gameover.wav");

        sound->stop();
    }
}

void GameRoom::moveUp()
{
    QPointF leftTop; // 左上角坐标
    QPointF rightBottom; // 右下角坐标

    auto snakeNode=snakeList.front(); // 头

    int headX = snakeNode.x();
    int headY = snakeNode.y();

    if(headY<0) // 穿墙了
    {
        leftTop=QPoint(headX,this->height()-kSnakeNodeHeight);
    }
    else
    {
        leftTop=QPoint(headX,headY-kSnakeNodeHeight);
    }

    rightBottom=leftTop+QPointF(kSnakeNodeWidth,kSnakeNodeHeight);

    snakeList.push_front(QRectF(leftTop,rightBottom));
}

void GameRoom::moveDown()
{
    QPointF leftTop; // 左上角坐标
    QPointF rightBottom; // 右下角坐标

    auto snakeNode=snakeList.front();

    int headX = snakeNode.x();
    int headY = snakeNode.y();

    if(headY>this->height()) // 穿墙了
    {
        leftTop=QPoint(headX,0);
    }
    else
    {
        leftTop=snakeNode.bottomLeft();
    }

    rightBottom=leftTop+QPointF(kSnakeNodeWidth,kSnakeNodeHeight);

    snakeList.push_front(QRectF(leftTop,rightBottom));
}

void GameRoom::moveLeft()
{
    QPointF leftTop; // 左上角坐标
    QPointF rightBottom; // 右下角坐标

    auto snakeNode=snakeList.front();

    int headX = snakeNode.x();
    int headY = snakeNode.y();

    if(headX<0) // 穿墙了
    {
        leftTop=QPoint(1100-kSnakeNodeWidth,headY);
    }
    else
    {
        leftTop=QPointF(headX-kSnakeNodeWidth,headY);
    }

    rightBottom=leftTop+QPointF(kSnakeNodeWidth,kSnakeNodeHeight);

    snakeList.push_front(QRectF(leftTop,rightBottom));
}

void GameRoom::moveRight()
{
    QPointF leftTop; // 左上角坐标
    QPointF rightBottom; // 右下角坐标

    auto snakeNode=snakeList.front();

    int headX = snakeNode.x();
    int headY = snakeNode.y();

    if(headX>1100) // 穿墙了
    {
        leftTop=QPoint(0,headY);
    }
    else
    {
        leftTop=snakeNode.topRight();
    }

    rightBottom=leftTop+QPointF(kSnakeNodeWidth,kSnakeNodeHeight);

    snakeList.push_front(QRectF(leftTop,rightBottom));
}

bool GameRoom::checkFail()
{
    for(int i=0;i<snakeList.size();i++)
    {
        for(int j=i+1;j<snakeList.size();j++)
        {
            if(snakeList.at(i)==snakeList.at(j))
            {
                return true;
            }
        }
    }
    return false;
}

void GameRoom::createNewFood()
{
    foodRect=QRectF(qrand()%(1150/kSnakeNodeWidth)*kSnakeNodeWidth,
                    qrand()%(this->height()/kSnakeNodeHeight)*kSnakeNodeHeight,
                    kSnakeNodeWidth,kSnakeNodeHeight);
}

















